import pymysql

# 数据库连接配置
host = '192.168.10.10'
port = 3307  # MySQL默认端口
user = 'root'
password = '123456'
database = 'saas_back'


def connect_to_mysql():
    global connection


try:
    # 建立数据库连接
    connection = pymysql.connect(
        host=host,
        port=port,
        user=user,
        password=password,
        database=database,
        charset='utf8mb4'
    )
    print("成功连接到MySQL数据库")
    # 这里可以进行数据库操作，例如创建游标、执行SQL语句等
    with connection.cursor() as cursor:
        sql = "SELECT * FROM users"
        cursor.execute(sql)
        # 插入一条数据
        sql_insert = "INSERT INTO users (id, user_name) VALUES (%s, %s)"
        # 删除数据
        #sql_delete = "DELETE FROM users WHERE user_name = %s"
        # 将名字为'Bob'的学生年龄修改为22岁
        # sql_update = "UPDATE users SET id = %s WHERE user_name = %s"
        data = (5, '赵四')
        cursor.execute(sql_insert, data)
        connection.commit()
        result = cursor.fetchone()
        print("数据库版本:", result)


finally:
    # 关闭数据库连接
    connection.close()
    print("已关闭MySQL数据库连接")


#